function initializeProfileCompletion(){
	hideLoadingLayer();
	var formParts = [];
	$(".CPFCformPart").each(function(){
		var formPart = $(this);
		formParts.push(formPart.attr("id"));
	});


	$("#CPFCComplete").addClass("hideClass");
	var selectedFormPartId = "CPFCName";
	var nextInactive = false;
	var backInactive = true;
	var hideAllFromParts = function(){
		for(var i=0; i<formParts.length; i++){
			var formPart = $("#"+formParts[i]);
			formPart.addClass("hideClass").css("opacity","0");
		}
	};
	hideAllFromParts();
	$("#CPFCName").removeClass("hideClass");
	$("#CPFCName").css("opacity", "1");
	var activateNextBackButton = function(next){
		var buttonActive = "";
		
		if(next==="next"){
			buttonActive = $("#CPFCNext");
		}else{
			buttonActive = $("#CPFCBack");
		}
		buttonActive.removeClass("disabledButton");
	};
	var disableNextBackButton = function(next)
	{
		var buttonInactive = "";
		if(next==="next"){
			buttonInactive = $("#CPFCNext");
		}else{
			buttonInactive = $("#CPFCBack");
		}
		buttonInactive.addClass("disabledButton");
	};
	activateNextBackButton("next");
	disableNextBackButton("back");
	var doNextBack = function(whatToDo){
		var indexToDisplay = 0;
		var currentIndex = formParts.indexOf(selectedFormPartId);
		if(whatToDo === "next"){
			debugger;
			if(!nextInactive){
				hideAllFromParts();
				indexToDisplay = currentIndex + 1;
				var itemToDisplay = $("#"+formParts[indexToDisplay]);
				itemToDisplay.removeClass("hideClass");
				itemToDisplay.css("opacity", "1");
				selectedFormPartId = formParts[indexToDisplay];
				if(indexToDisplay + 1 >= formParts.length){
					nextInactive = true;
					disableNextBackButton("next");
					$("#CPFCNext").addClass("hideClass");
					$("#CPFCComplete").removeClass("hideClass");
				}
				backInactive = false;
				activateNextBackButton("back");
			}
		}else{
			if(!backInactive){
				debugger;
				hideAllFromParts();
				indexToDisplay = currentIndex - 1;
				var itemToDisplay = $("#"+formParts[indexToDisplay]);
				itemToDisplay.removeClass("hideClass");
				itemToDisplay.css("opacity", "1");
				selectedFormPartId = formParts[indexToDisplay];
				if(indexToDisplay - 1 < 0){
					backInactive = true;
					disableNextBackButton("back");
				}
				$("#CPFCComplete").addClass("hideClass");
				$("#CPFCNext").removeClass("hideClass");
				nextInactive = false;
				activateNextBackButton("next");
			}
		}
	};

	$("#CPFCNext").on("click", function(){
		doNextBack("next");
	});
	$("#CPFCBack").on("click", function(){
		doNextBack("back");
	});


	$("#CPFCComplete").on("click", function(){
		if(validateCompleteRegistrationForm()){
			debugger;	
			showLoadingLayer();		
			var responseFunction = function(r){
				hideLoadingLayer();
				debugger;
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					var params = {
						action: "showProfile"
					};
					var url = getURL("profile.php");
					showLoadingLayer();
					$.post(url, params, displayProfile);
				}
			};
			var theForm = $("form[name='completeProfileForm']");
			var options = {
				success: responseFunction,
				resetForm: false
			};
			theForm.ajaxSubmit(options);
		}
	});

	initializePostcode("#postcode", "#address");

	initializeProfilePictureUploaders();

}

function validateCompleteRegistrationForm(){
	debugger;
	var message = "";
	var errMessages = [];
	errMessages.push(validateField("firstName", ["empty","textonly"]));
	errMessages.push(validateField("secondName", ["textonly"]));
	errMessages.push(validateField("firstLastname", ["empty","textonly"]));
	errMessages.push(validateField("secondLastname", ["textonly"]));
	errMessages.push(validateField("firstName", ["empty","textonly"]));
	errMessages.push(validateField("postcode", ["empty","postcode"]));
	errMessages.push(validateField("address", ["empty"]));
	errMessages.push(validateField("dateOfBirth", ["empty", "dateOfBirth"]));
	debugger;
	message = concatArray(message, errMessages);
	if(message.trim() !== ""){
		alert(message);
		return false;
	}
	return true;
}
function getAddress(postcode, outputFunction, coordsFunction){
	var result = "";
	$.post('http://maps.googleapis.com/maps/api/geocode/json?components=country:GB|postal_code:'+postcode+', UK&sensor=false&language=en', function(r) {
			debugger;
			if(!r['results'][0]){
				outputFunction("Please type your address here");
				return;
			}
			var lat = r['results'][0]['geometry']['location']['lat'];
			var lng = r['results'][0]['geometry']['location']['lng'];
			if(coordsFunction){
				coordsFunction(lat, lng);
			}
			var coords = {
				lat: lat,
				lng: lng
			};
			getAddressLatLng(coords, outputFunction);
		});
	return result;
}
function getAddressLatLng(coords, outputFunction)
{
	var lat = coords.lat;
	var lng = coords.lng;
	$.post('http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lng+'&sensor=false&language=en', function(address) {
			result = address['results'];
			/*result = address['results'][0]['address_components'][0]['long_name'];
			result += " " + address['results'][0]['address_components'][1]['long_name'];
			result += " " + address['results'][0]['address_components'][2]['long_name'];
			result += " " + address['results'][0]['address_components'][3]['long_name'];*/
			outputFunction(result);
	});
}
function initializePostcode(fieldId, addressFieldId){
	var addressId;
	if(addressFieldId){
		addressId = addressFieldId;
	}else
	{
		addressId = "#address";
	}

	var showAddress  = function(result){
		debugger;
		var resultStr = "";
		result = result[0]['address_components'];
		for(var i = 0; i<4; i++){
			resultStr += " " + result[i]['long_name'];
		}
		$(addressId).val(resultStr);
	};
	$(fieldId).on("change",function(){
			debugger;
			var postcode = $(this).val().trim();
			if(validatePostCode(postcode)){
				getAddress(postcode, showAddress);
			}else{
				alert("Not a valid postcode");
			}
	});
}

function showThumbnail(file,inputFileId)
{
    var previewerId = "#" + inputFileId + "Previewer";
    if (!file || !window.FileReader){
    	return; // no file selected, or no FileReader support
    } 

    if (/^image/.test( file.type)){ // only image file
        var reader = new FileReader(); // instance of the FileReader
        reader.readAsDataURL(file); // read the local file
			
        reader.onloadend = function(){ // set image data as background of div
            $(previewerId).css("background-image", "url("+this.result+")");
            $(previewerId).css("display", "block");
        }
    }else{
    }
}
function initializeProfilePictureUploaders(){
		$("input[type=file]").each(function (){
		$(this).on("change", function(event){
			debugger;
			var id = $(this).attr("id");
			var file = event.target.files[0];
			showThumbnail(file, id);			
		});

		});

		debugger;
		$("#CPFCEditPhotos > div a").each(function(){
			var thisObj = this;
			$(thisObj).on("click", function(){
				$(thisObj).next().trigger("click");
			});
		});
	}

function initializeEditProfile(r){
	debugger;
	var r = JSON.parse(r);
	if(!r || r.error){
		alert("There was an error. Please try again later");
	}
	hideLoadingLayer();
	configureListingAndProfileLayer(r);
	//initializeProfilePictureUploaders();
	initializePostcode("#postcode", "#address");
	$("#CPFCExitEditProfile").on("click", function(){$("#profileButton").trigger("click");});
	var updateProfile = function()
	{
		if(validateCompleteRegistrationForm())
		{
			showLoadingLayer();
			var responseFunction = function(r){
				debugger;
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					$("#profileButton").trigger("click");
				}
			};
			var theForm = $("form[name='editProfileForm']");
			var options = {
				success: responseFunction,
				resetForm: false
			};
			theForm.ajaxSubmit(options);
		}
	}
	$("#CPFCCompleteEdit").on("click", updateProfile);
	$("#editProfileImages").on("click", function(){
		showLoadingLayer();
		debugger;
		var responseFunction = function(r){
				debugger;
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					initializeProfileImagesEditor(r);
				}
			};
		var url = getURL("profile.php");
		var params = {action : "getProfileImagesEditor"};
		$.post(url, params, responseFunction);
	});
}

function initializeProfileImagesEditor(r)
{
	debugger;
	var pu;
	configureListingAndProfileLayer(r);
	var theFormEl = $("<form method=\"post\" enctype=\"multipart/form-data\" id=\"listingForm\" action=\"processImages.php\" style=\"display: none;\"></form>");
	var theImages = [];
	var imagesObj = r.picturesUrl;

	var uploadImageFx = function(theForm, afterUploadFx)
	{
		showLoadingLayer();
		var afterUpload = function(r)
		{
			hideLoadingLayer();
			afterUploadFx(r);
			pu.enableButtonsWhenNoPictures($("#PU-set"), setImage);
			disableCroppingOptions();
			enablePictureOptions();
		};
 		theForm.append($("<input type=\"hidden\" name=\"action\" value=\"addUserImage\"></input>"));
			var options = {
			success: afterUpload,
			resetForm: false
		};
		
		theForm.ajaxSubmit(options);
	}

	var deleteImageFx = function(image, afterDeleteFx)
	{
		debugger;
		showLoadingLayer();
		var afterDelete = function(r)
		{
			hideCropSaver();
			hideLoadingLayer();
			r = JSON.parse(r);
			if(!r.error)
			{
				afterDeleteFx(image);
			}
			if(pu.uploadedPictureCount() == 0)
			{
				pu.disableButtonsWhenNoPictures($("#PU-set"));
				pu.disableButtonsWhenNoPictures($("#PU-crop"));
			}
			if(image.pk == pu.imageSet.pk)
			{
				pu.imageSet = null;
			}
			showListingPicutrePreview();
		};
		var params = {
			action: "removeUserImage",
			pk: image.imagePk
		};
		var url = getURL("processImages.php");
		$.post(url, params, afterDelete);
	}
	var setMainImageFx = function(theImage, afterSetImageFx)
	{
		showLoadingLayer();
		var params = 
		{	
			action: "setUserImage",
			pk: theImage.imagePk
		};
		var afterSet = function(r)
		{
			hideLoadingLayer();
			r = JSON.parse(r);
			if(r && !r.error)
			{
				alert("The image was set successfully");
				enablePictureOptions();
			}
			else
			{
				alert("There was an error. Please try again later.");
			}
			afterSetImageFx();
			showListingPicutrePreview();
		}
		var url = getURL("processImages.php");
		$.post(url, params, afterSet);
	}

	var afterNext = function()
	{
		enablePictureOptions();
	};

	var afterBack = function()
	{
		enablePictureOptions();
	};

	var afterThumbClickFx = function()
	{
		enablePictureOptions();
	};

	/*var validImageMinHeight = 390;
	var validImageMinWidth = 488;*/
	var validImageMinHeight = 640;
	var validImageMinWidth = 360;
	var imageValidator = new ImageValidator(validImageMinWidth, validImageMinHeight);

	var theImages = [];
	for(var i=0; i < r.picturesUrl.length; i++)
	{
		var imageInfo = r.picturesUrl[i];
		var theImageUrl = imageInfo.picture_url;
		var thePk = imageInfo.pk;
		var mainPicture = imageInfo.mainPicture;
		var width = imageInfo.width;
		var height = imageInfo.height;
		var cropped = parseInt(imageInfo.cropped);
		var theImage = {
			pk: thePk,
			url: theImageUrl,
			cssClass: "thumbClass",
			width: width,
			height: height,
			cropped: cropped,
			croppedUrl: imageInfo.cropped_picture_url
		};
		
		if(mainPicture == 1)
		{
			theImage.selected = true;
		}

		theImages.push(theImage);
	}
	var noPictureEl = "<div><p>You can upload pictures by pressing the add button below</p><a href=\"#\" class=\"PU-button\" onclick=\"(function(){$(\'#PU-add\').trigger(\'click\');})(event)\"><i class=\"flaticon-round69\"></i> </a></div>"; 
	var parameters = 
	{
		theFormEl: theFormEl,
		addButtonEl: $("#PU-add"),
		deleteButton: $("#PU-delete"),
		nextBttnEl: $("#PU-next"),
		backBttnEl: $("#PU-back"),
		previewerEl: $("#PU-previewer"),
		thumbsContainerEl: $("#PU-thumbs"),
		setImageFx: setMainImageFx,
		deleteImageFx: deleteImageFx,
		uploadImageFx: uploadImageFx,
		theImages: theImages,		
		numberImagesToShow: 4,
		imageValidatorFx: imageValidator.validate,
		afterNextFx: afterNext,
		afterBackFx: afterBack,
		afterThumbClickFx: afterThumbClickFx,
		noPictureEl: $.parseHTML(noPictureEl),
		selectedThumbClass: "selectedThumb"

	}

	pu = new PictureUploader(parameters);
	$("#PU-cancel").on("click", function(){
		showLoadingLayer();
		showEditProfile();
	});
	var saveCroppedImage = function(afterSave)
	{
		showLoadingLayer();
		var imageObj = pu.getImageInPreviewer();
		
		var data = imageObj.imageEl.cropper("getData");
		var params = 
		{
			action: "cropUserImage",
			url: imageObj.imageUrl,
			pk: imageObj.pk,
			height: data.height,
			width: data.width,
			x: data.x,
			y: data.y
		};
		var url = getURL("processImages.php");
		var afterCrop = function(r)
		{
			debugger;
			r = JSON.parse(r);
			if(r && !r.error)
			{
				pu.getImageInPreviewer().rawObj.croppedUrl = r.cropped_picture_url;
				if(pu.imageSet && pu.getImageInPreviewer().pk == pu.imageSet.imagePk)
				{
					pu.imageSet = pu.getImageInPreviewer();
					showListingPicutrePreview();
				}
				hideLoadingLayer();
				afterSave();
			}
		}
		$.post(url, params, afterCrop);
	};

	var setImage = function()
	{
		if(pu.uploadedPictureCount() == 0)
		{
			alert("Please upload a picture first");
			return;
		}
		var imageInPreviewer = pu.getImageInPreviewer();
		if(!imageInPreviewer.rawObj.cropped)
		{
			alert("Please crop your image.");
			var afterCrop = function()
			{
				pu.fireSet();
			}
			cropImage(afterCrop);
		}
		else
		{
			pu.fireSet();
		}
		
		
	}
	var croppingOptionsEnabled = false;
	var doCancelCrop = function()
	{
		disableCroppingOptions();
		pu.getImageInPreviewer().imageEl.cropper("destroy");
	}
	var enableCroppingOptions = function()
	{
		if(!croppingOptionsEnabled)
		{
			$("#PU-additionalControl").removeClass("hideClass");
			$("#cropCancel").on("click", doCancelCrop);
			disablePictureOptions();
			croppingOptionsEnabled = true;
		}		
	}
	var disableCroppingOptions = function()
	{
		if(croppingOptionsEnabled)
		{
			$("#PU-additionalControl").addClass("hideClass");
			//$("#cropSaver").off("click");
			$("#cropCancel").off("click");
			enablePictureOptions();
			croppingOptionsEnabled = false;			
		}	
	}
	var enablePictureOptions = function()
	{
		disablePictureOptions();
		$("#PU-control").removeClass("hideClass");
		$("#PU-set").on("click", setImage).css("opacity", "1").css("cursor", "pointer");
		pu.enableButtonsWhenNoPictures($("#PU-delete"), pu.imageDeleter);
		$("#PU-crop").on("click", function(){cropImage();}).css("opacity", "1").css("cursor", "pointer");
	}
	var disablePictureOptions = function()
	{
		$("#PU-control").addClass("hideClass");
		$("#PU-set").off("click").css("opacity", "0.4").css("cursor", "default");
		pu.disableButtonsWhenNoPictures($("#PU-delete"));
		$("#PU-crop").off("click").css("opacity", "0.4").css("cursor", "default");
	}
	var cropImage = function(afterCrop)
	{
		enableCroppingOptions();
		var afterSave = function()
		{
			$("#cropCancel").trigger("click");
			disableCroppingOptions();
			pu.getImageInPreviewer().rawObj.cropped = 1;
			if(afterCrop)
			{
				afterCrop();
			}
			else
			{
				alert("Your image was cropped successfully");
			}
		}
		var save = function()
		{
			saveCroppedImage(afterSave);
		}
		$("#cropSaver").off("click");
		$("#cropSaver").on("click", save);
		var imageObj = pu.getImageInPreviewer();
		var imageEl = imageObj.imageEl;
		imageEl.cropper({
		  /*aspectRatio: 86/81,*/
		  aspectRatio: 32/18,
		  preview: ".img-preview",
		  resizable: true,
		  dragCrop: false,
		  minWidth:imageValidator.minWidth,
		  minHeight: imageValidator.minHeight
		});
	}
	enablePictureOptions();

	if(pu.uploadedPictureCount() == 0)
	{
		disablePictureOptions();
		$("#PU-control").removeClass("hideClass");
	}

	var showListingPicutrePreview = function()
	{
		debugger;
		var image = pu.imageSet;
		var url;
		if(image)
		{
			url = pu.imageSet.rawObj.croppedUrl;
		}
		else
		{
			url = "img/no-pic.jpeg";
		}
		$("#PU-current-selected-picture").css("background-image","url('"+url+"')");
	};
	showListingPicutrePreview();
	hideLoadingLayer();	

}

function initializeListingImagesEditor(r)
{
	var pu;
	configureListingAndProfileLayer(r);
	var theFormEl = $("<form method=\"post\" enctype=\"multipart/form-data\" id=\"listingForm\" action=\"processImages.php\" style=\"display: none;\"></form>");
	var theImages = [];
	var imagesObj = r.picturesUrl;

	var uploadImageFx = function(theForm, afterUploadFx)
	{
		showLoadingLayer();
		var afterUpload = function(r)
		{
			hideLoadingLayer();
			afterUploadFx(r);
			pu.enableButtonsWhenNoPictures($("#PU-set"), setImage);
			disableCroppingOptions();
			enablePictureOptions();
		};
 		theForm.append($("<input type=\"hidden\" name=\"action\" value=\"addResultImage\"></input>"));
			var options = {
			success: afterUpload,
			resetForm: false
		};
		
		theForm.ajaxSubmit(options);
	}

	var deleteImageFx = function(image, afterDeleteFx)
	{
		showLoadingLayer();
		var afterDelete = function(r)
		{
			hideLoadingLayer();
			r = JSON.parse(r);
			if(!r.error)
			{
				afterDeleteFx(image);
			}
			if(pu.uploadedPictureCount() == 0)
			{
				pu.disableButtonsWhenNoPictures($("#PU-set"));
				pu.disableButtonsWhenNoPictures($("#PU-crop"));
			}
			if(image.pk === pu.imageSet.pk)
			{
				pu.imageSet = null;
			}
			showListingPicutrePreview();
		};
		var params = {
			action: "removeResultImage",
			pk: image.imagePk
		};
		var url = getURL("processImages.php");
		$.post(url, params, afterDelete);
	}
	var setMainImageFx = function(theImage, afterSetImageFx)
	{
		showLoadingLayer();
		var params = 
		{	
			action: "setResultImage",
			pk: theImage.imagePk
		};
		var afterSet = function(r)
		{
			debugger;
			hideLoadingLayer();
			r = JSON.parse(r);
			if(r && !r.error)
			{
				alert("The image was set successfully");
				enablePictureOptions();
			}
			else
			{
				alert("There was an error. Please try again later.");
			}
			afterSetImageFx();
			showListingPicutrePreview();
		}
		var url = getURL("processImages.php");
		$.post(url, params, afterSet);
	}

	var afterNext = function()
	{
		enablePictureOptions();
	};

	var afterBack = function()
	{
		enablePictureOptions();
	};

	var afterThumbClickFx = function()
	{
		enablePictureOptions();
	};

	var validImageMinHeight = 640;
	var validImageMinWidth = 360;
	var imageValidator = new ImageValidator(validImageMinWidth, validImageMinHeight);

	var theImages = [];
	for(var i=0; i < r.picturesUrl.length; i++)
	{
		var imageInfo = r.picturesUrl[i];
		var theImageUrl = imageInfo.picture_url;
		var thePk = imageInfo.pk;
		var mainPicture = imageInfo.main_picture;
		var width = imageInfo.width;
		var height = imageInfo.height;
		var cropped = parseInt(imageInfo.cropped);
		var theImage = {
			pk: thePk,
			url: theImageUrl,
			cssClass: "thumbClass",
			width: width,
			height: height,
			cropped: cropped,
			croppedUrl: imageInfo.cropped_picture_url
		};
		
		if(mainPicture == 1)
		{
			theImage.selected = true;
		}

		theImages.push(theImage);
	}
	var noPictureEl = "<div><p>You can upload pictures by pressing the add picture button.</p><a href=\"#\" class=\"PU-button\" onclick=\"(function(){$(\'#PU-add\').trigger(\'click\');})(event)\"><i class=\"flaticon-round69\"></i> </a></div>";
	var parameters = 
	{
		theFormEl: theFormEl,
		addButtonEl: $("#PU-add"),
		deleteButton: $("#PU-delete"),
		nextBttnEl: $("#PU-next"),
		backBttnEl: $("#PU-back"),
		previewerEl: $("#PU-previewer"),
		thumbsContainerEl: $("#PU-thumbs"),
		setImageFx: setMainImageFx,
		deleteImageFx: deleteImageFx,
		uploadImageFx: uploadImageFx,
		theImages: theImages,		
		numberImagesToShow: 4,
		imageValidatorFx: imageValidator.validate,
		afterNextFx: afterNext,
		afterBackFx: afterBack,
		afterThumbClickFx: afterThumbClickFx,
		noPictureEl: $.parseHTML(noPictureEl),
		selectedThumbClass: "selectedThumb"
	}

	pu = new PictureUploader(parameters);
	$("#PU-cancel").on("click", function(){
		showLoadingLayer();
		showEditListing();
	});
	var saveCroppedImage = function(afterSave)
	{
		showLoadingLayer();
		var imageObj = pu.getImageInPreviewer();
		var data = imageObj.imageEl.cropper("getData");
		var params = 
		{
			action: "cropResultImage",
			url: imageObj.imageUrl,
			pk: imageObj.pk,
			height: data.height,
			width: data.width,
			x: data.x,
			y: data.y
		};
		var url = getURL("processImages.php");
		var afterCrop = function(r)
		{	
			debugger;
			r = JSON.parse(r);
			if(r && !r.error)
			{
				pu.getImageInPreviewer().rawObj.croppedUrl = r.cropped_picture_url;
				if(pu.imageSet && pu.getImageInPreviewer().pk == pu.imageSet.imagePk)
				{
					pu.imageSet = pu.getImageInPreviewer();
					showListingPicutrePreview();
				}
				hideLoadingLayer();
				afterSave();
			}
		}
		$.post(url, params, afterCrop);
	};
	var setImage = function()
	{
		if(pu.uploadedPictureCount() == 0)
		{
			alert("Please upload a picture first");
			return;
		}
		var imageInPreviewer = pu.getImageInPreviewer();
		if(!imageInPreviewer.rawObj.cropped)
		{
			alert("Please crop your image.");
			var afterCrop = function()
			{
				pu.fireSet();
			}
			cropImage(afterCrop);
		}
		else
		{
			pu.fireSet();
		}
		
		
	}
	var croppingOptionsEnabled = false;
	var doCancelCrop = function()
	{
		disableCroppingOptions();
		pu.getImageInPreviewer().imageEl.cropper("destroy");
	}
	var enableCroppingOptions = function()
	{
		if(!croppingOptionsEnabled)
		{
			$("#PU-additionalControl").removeClass("hideClass");
			$("#cropCancel").on("click", doCancelCrop);
			disablePictureOptions();
			croppingOptionsEnabled = true;
		}		
	}
	var disableCroppingOptions = function()
	{
		if(croppingOptionsEnabled)
		{
			$("#PU-additionalControl").addClass("hideClass");
			//$("#cropSaver").off("click");
			$("#cropCancel").off("click");
			enablePictureOptions();
			croppingOptionsEnabled = false;			
		}	
	}
	var enablePictureOptions = function()
	{
		disablePictureOptions();
		$("#PU-control").removeClass("hideClass");
		$("#PU-set").on("click", setImage).css("opacity", "1").css("cursor", "pointer");
		pu.enableButtonsWhenNoPictures($("#PU-delete"), pu.imageDeleter);
		$("#PU-crop").on("click", function(){cropImage();}).css("opacity", "1").css("cursor", "pointer");
	}
	var disablePictureOptions = function()
	{
		$("#PU-control").addClass("hideClass");
		$("#PU-set").off("click").css("opacity", "0.4").css("cursor", "default");
		pu.disableButtonsWhenNoPictures($("#PU-delete"));
		$("#PU-crop").off("click").css("opacity", "0.4").css("cursor", "default");
	}
	var cropImage = function(afterCrop)
	{
		enableCroppingOptions();
		var afterSave = function()
		{
			$("#cropCancel").trigger("click");
			disableCroppingOptions();
			pu.getImageInPreviewer().rawObj.cropped = 1;
			if(afterCrop)
			{
				afterCrop();
			}
			else
			{
				alert("Your image was cropped successfully");
			}
		}
		var save = function()
		{
			saveCroppedImage(afterSave);
		}
		$("#cropSaver").off("click");
		$("#cropSaver").on("click", save);
		var imageObj = pu.getImageInPreviewer();
		var imageEl = imageObj.imageEl;
		debugger;
		imageEl.cropper({
		  aspectRatio: 32/18,
		  preview: ".img-preview",
		  resizable: true,
		  dragCrop: false,
		  minWidth:imageValidator.minWidth,
		  minHeight: imageValidator.minHeight
		});
	}
	enablePictureOptions();

	if(pu.uploadedPictureCount() == 0)
	{
		disablePictureOptions();
		$("#PU-control").removeClass("hideClass");
	}

	var showListingPicutrePreview = function()
	{
		debugger;
		var image = pu.imageSet;
		var url;
		if(image)
		{
			url = pu.imageSet.rawObj.croppedUrl;
		}
		else
		{
			url = "img/no-pic.jpeg";
		}
		$("#PU-current-selected-picture").css("background-image","url('"+url+"')");
	};
	showListingPicutrePreview();
	hideLoadingLayer();
}

function showEditProfile()
{
	var url = getURL("profile.php");
	var params = {action : "getProfileEditor"};
	$.post(url, params, initializeEditProfile);
}


function showEditListing()
{
	var url = getURL("profile.php");
	var params = {action : "getListingTypeSelector"};
	$.post(url, params, initializeListingTypeSelector);
}

function initializeProfile(){

	$("#editProfileButton").on("click", function(){
		debugger;
		showLoadingLayer();
		showEditProfile();
	});

	$("#createListingButton").on("click", function(){
		showLoadingLayer();
		var url = getURL("profile.php");
		var params = {action : "getListingTypeSelector"};
		$.post(url, params, initializeListingTypeSelector);
	});
}

function validateListingForm()
{
	return true;
}
function initializeListingTypeSelector(r)
{
	
	r = JSON.parse(r);
	hideLoadingLayer();
	if(r && !r.error)
	{
		configureListingAndProfileLayer(r);
		$("#typeofListing").on("change", function(){
			var action = $("#typeofListing").val();
			if(action.trim() === "")
			{
				return;
			}
			var url = getURL("profile.php");
			var listingCathegories = 
				{
					_1: "getLEPersonal",
					_2: "getLEHotel",
					_3: "getLERestaurant",
					_4: "getLEBar",
					_5: "getLEEntertainment"
				};
			var params = 
			{
				action: listingCathegories["_"+action]
			}
			$.post(url, params, initializeListingEditorForm);
			showLoadingLayer();
		});
		if(r.typeSelected !== "")
		{
			$("#typeofListing").trigger("change");
		}
	}
}
function initializeListingEditorForm(r){
	hideLoadingLayer();
	r = JSON.parse(r);
	if(r && !r.error)
	{
		configureListingEditor(r.htmlString);
		initializeListingEditor();
	}
}
function initializeListingEditor(){
	//Location details initilizer
	var myLatLng = new google.maps.LatLng(51.512161, -0.129089);
	var styles =
      [
      {
            stylers: [
                  {
                  hue: "#ff1a00"
                  },
                  {
                  invert_lightness: true
                  },
                  {
                  saturation: -100
                  },
                  {
                  lightness: 33
                  },
                  {
                  gamma: 0.5
                  }
            ]
    },

      {
            featureType: "water",
            elementType: "geometry",
            stylers: [
                  {
                  color: "#2D333C"
                  }
            ]
      }
      ];
    var mapOptions = {
        center: myLatLng,
        zoom: 13,
        mapTypeControl: false,
        scaleControl: false,
        navigationControl: false,
        streetViewControl: false,
        disableDefaultUI: true,
        styles: styles,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
    var canvas = $("#LE-locationDetailsMap") && $("#LE-locationDetailsMap")[0];
    var map = new google.maps.Map(canvas, mapOptions); 

	var addressMarker = new google.maps.Marker({
	    position: myLatLng, 
	    map: map, // handle of the map 
	    draggable:true,
	    visible: true
	});

	var displayDividedAddress = function(result){
		debugger;
		if(!result[0] || !result[0]['address_components'])
		{
			return;
		}
		$("#coordsLatListing").val(result[1].geometry.location.lat);
		$("#coordsLngListing").val(result[1].geometry.location.lng);
		$("#cityListing").val(window.results.getCityFromLocation(result[0]['address_components']));
		$("#areaListing").val(result[0]['address_components'][2]['long_name']);
		$("#streetNameListing").val(result[0]['address_components'][1]['long_name']);
		$("#houseNumberListing").val(result[0]['address_components'][0]['long_name']);
		$("#postcodeListing").val(result[0]['address_components'][result[0]['address_components'].length-1]['long_name']);
	};

	google.maps.event.addListener(addressMarker, "dragend", function(event) { 
      var coords = {
      	lat: event.latLng.lat(),
      	lng: event.latLng.lng()
      };
      getAddressLatLng(coords, displayDividedAddress);
    });

	$("#postcodeListing").on("change", function(){
		var postcode = $(this).val().trim();
		var saveCoords = function(lat, lng){
			$("#latitude").val(lat);
			$("#longitude").val(lng);
		}
		if(validatePostCode(postcode)){
			var processCoords = function(lat, lng)
			{
				saveCoords(lat, lng);
				var latLng = new google.maps.LatLng(lat, lng);
				addressMarker.setPosition(latLng);
				map.setCenter(latLng)
			};
			getAddress(postcode, displayDividedAddress, processCoords);
		}else{
			alert("Not a valid postcode");
		}
	});
	if($("#postcodeListing").val().trim() !== "")
	{
		$("#postcodeListing").trigger("change");
	}
	$("#editListingImages").on("click", function(){
		showLoadingLayer();
		var url = getURL("profile.php");
		var params = {
			action: "getResultImagesEditor"
		};
		var afterFx = function(r)
		{
			hideLoadingLayer();
			r = JSON.parse(r);
			initializeListingImagesEditor(r);
		}
		$.post(url, params, afterFx);
	});
	$("#LE-submitButton").on("click", function(){
		var message = "";
		var errMessages = [];
		errMessages.push(validateField("nameListing", ["empty"]));
		errMessages.push(validateField("descriptionListing", ["empty"]));
		errMessages.push(validateField("priceListing", ["empty","number"]));
		errMessages.push(validateField("postcodeListing", ["empty","postcode"]));
		errMessages.push(validateField("cityListing", ["empty", "textonly"]));
		errMessages.push(validateField("areaListing", ["empty"]));
		errMessages.push(validateField("streetNameListing", ["empty"]));
		errMessages.push(validateField("telephoneListing", ["empty"]));
		errMessages.push(validateField("emailListing", ["empty","email"]));
		message = concatArray(message, errMessages);
		if(message.trim() !== ""){
			alert(message);
			return;
		}
		var responseFunction = function(r){
				hideLoadingLayer();
				r = JSON.parse(r);
				if(r && r.error){
					alert("There was an error. Please try again.");
				}
				else
				{
					$("#profileButton").trigger("click");
				}
			};
			var theForm = $("#listingForm");
			var options = {
				success: responseFunction,
				resetForm: false
			};
			theForm.ajaxSubmit(options);
	});
	$("#LE-cancelButton").on("click", function(){
		if(confirm("Are you sure you want to cancel?"))
		{
			$("#profileButton").trigger("click");
		}
	});

}
function displayProfile(r){
	debugger;
	hideLoadingLayer();
	r = JSON.parse(r);
	var error = false;
	if(!r || r.error){
		alert("There was an error. Please try again later");
	}else{
		configureLoginLayer(r);
		initializeProfile();
	}
};

var hiddenElements = [];
function displayForm(){
	displayListingElements(hiddenElements);
	clearArray(hiddenElements);
	var elementsToHide = [];
	var typeofListing = $(this).val();
	switch(typeofListing){
		case "1":
			elementsToHide = ["hotelRatingListing","hotelRulesListing", "openingTimeListing", "cancellationFeeListing"];
			break;
		case "2":
			elementsToHide = ["extraPeopleListing","houseRulesListing", "openingTimeListing","weekPriceListing", "monthPriceListing", "bedroomsListing", "cancellationFeeListing"];
			break;
		case "3":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];
			break;
		case "4":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];			
			 break;
		case "5":
			elementsToHide = ["roomTypeListing","bedTypeListing", "acomodatesListing", "bedroomsListing", "bedsListing",
			 "extraPeopleListing", "weekPriceListing", "monthPriceListing",
			 "cancellationListing", "cancellationFeeListing", "houseRulesListing", "hotelRulesListing",
			 "hotelRatingListing"];
			 break;
		default:
			$("#listingFormBody").addClass("hideClass");
			break;
	}
	hideElements(elementsToHide, false);
	if(typeofListing && typeofListing !== ""){
		$("#listingFormBody").removeClass("hideClass");;
	}
}

function hideElements(elementsToHide){
	for(var i = 0; i<elementsToHide.length; i++){
				hideListingFormElement(elementsToHide[i]);
	}
}
function hideListingFormElement(id){
	var label = $("label[for='"+id+"']");
	var element = $("#"+id);
	label.addClass("hideClass");
	element.addClass("hideClass");
	hiddenElements.push(id);
}

function displayListingElements(listingElementsToShow){
	for(var i = 0; i<listingElementsToShow.length; i++){
		showListingElement(listingElementsToShow[i]);
	}
}

function showListingElement(id){
	var label = $("label[for='"+id+"']");
	var element = $("#"+id);
	label.removeClass("hideClass");
	element.removeClass("hideClass");
}